import axios from 'axios'
import store from '@/store'
import { refreshToken } from '@/api/user'

const request = axios.create({
  baseURL: 'http://39.97.218.60'
})

// 请求拦截器
request.interceptors.request.use(function (config) {
  config.headers.Authorization = store.state.tokenInfo?.access_token
  return config
})

// 响应拦截器
request.interceptors.response.use(
  // 成功的回调
  function (response) {
    return response
    // 失败的回调
  }, function (error) {
    if (error.response.status === 401) {
      return refreshToken().then(() => {
        return request(error.config)
      })
    } else {
      return Promise.reject(error)
    }
  })

export default request
